import axios from 'axios'
const config = {}

function loadConfig () {
    const contextPath = getContextPath()
    config.contextPath = contextPath

    const promises = []
    promises.push(axios.get(contextPath + '/config.json'))

    if (Promise && !Promise.allSettled) {
      Promise.allSettled = function (promises) {
        return Promise.all(promises.map(function (promise) {
          return promise.then(function (value) {
            return {
              status: 'fulfilled',
              value: value
            }
          }).catch(function (reason) {
            return {
              status: 'rejected',
              reason: reason
            }
          })
        }))
      }
    }

    return new Promise((resolve, reject) => {
        Promise.allSettled(promises).then(([configResp]) => {
            if (configResp.status === 'fulfilled') {
                const configData = configResp.value.data || {}
                let serviceUrl = configData.serviceUrl || ''
                serviceUrl = getServiceUrl(contextPath, serviceUrl)

                config.serviceUrl = serviceUrl
                resolve(config)
            } else {
                reject(configResp)
            }
        })
    })
}

function pathConcat (path1, path2) {
    let path = null
    if (!path1 || !path2) {
        path = path1 || path2
    } else {
        if (/^\.\//.test(path2)) {
            path2 = path2.replace('./', '')
        } else if (/\//.test(path2)) {
            path2 = path2.replace(/^\//, '')
        }
        while (/^\.\.\//.test(path2) && !/^[\s]*$/.test(path1)) {
            path2 = path2.replace('../', '')
            if (path1.lastIndexOf('/') == -1) {
                path1 = ''
            } else {
                path1 = path1.substr(0, path1.lastIndexOf('/'))
            }
        }
        if (!path1 || !path2) {
            path = path1 || path2
        } else if (/\/$/.test(path1)) {
            path = path1 + path2
        } else {
            path = path1 + '/' + path2
        }
    }
    return path
}

function pathConcats () {
    let path = null
    if (arguments) {
        for (let i = 0; i < arguments.length; i++) {
            path = pathConcat(path, arguments[i])
        }
    }
    return path
}

function isHttpUrl (url) {
    return /^http(s)?:\/\/[^\/]{1,}/.test(url)
}

function httpUrlConcat (httpUrl, path) {
    let url = ''
    if (!httpUrl || !path) {
        url = httpUrl || path
    } else if (!isHttpUrl(httpUrl)) {
        return pathConcats(httpUrl, path)
    } else {
        const idx = httpUrl.indexOf('/', 9)
        const path1 = idx === -1 ? httpUrl : httpUrl.substring(0, idx)
        const path2 = idx === -1 ? '' : httpUrl.substring(idx)
        url = pathConcats(path2, path)
        if (/^\.\.\//.test(url)) {
            throw new Error('未找到服务地址')
        } else {
            url = path1 + '/' + url.replace(/^\//, '')
        }
    }
    return url
}

function getServiceUrl (contextPath, serviceUrl) {
    let prefix = window.config.VUE_APP_BASE_URL || ''
    if (!prefix) {
        prefix = serviceUrl
    }
    if (!prefix) {
        if (isHttpUrl(contextPath)) {
            prefix = contextPath
        } else if (contextPath) {
            throw new Error('未找到服务地址')
        }
    } else if (!isHttpUrl(prefix) && contextPath) {
        // 服务地址不是http或者https开头
        const idx = contextPath.indexOf('/', 9)
        const path1 = idx === -1 ? contextPath : contextPath.substring(0, idx)
        const path2 = idx === -1 ? '' : contextPath.substring(idx)
        prefix = pathConcats(path2, prefix)
        if (/^\.\.\//.test(prefix)) {
            throw new Error('未找到服务地址')
        } else {
            prefix = path1 + '/' + prefix.replace(/^\//, '')
        }
    }
    if (prefix) prefix = prefix.replace(/\/$/, '')
    console.info('ServiceUrl: ' + prefix)
    return prefix
}

function getContextPath () {
    let contextPath = location.pathname
    contextPath = contextPath.substring(0, contextPath.lastIndexOf('/'))
    contextPath = location.protocol + '//' + location.host + contextPath
    console.info('ContextPath: ' + contextPath)
    return contextPath
}

export default {
    loadConfig: loadConfig,
    getServiceUrl: () => {
        return config.serviceUrl
    },
    getContextPath: () => {
        return config.contextPath
    },
    buildRequestUrl: (url) => {
        const serviceUrl = config.serviceUrl
        if (!isHttpUrl(url) && serviceUrl) {
            url = httpUrlConcat(serviceUrl, url)
        }
        return url
    }
}
